package org.zfes.snowy.ss.config.configrations;

import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;

import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

@Configuration  
public class RestTemplateConfig {
	@Autowired
	FastJsonConfigration fastJsonConfigration;
	
	 @Bean  
	 public RestTemplate restTemplate(ClientHttpRequestFactory factory){  
		 RestTemplate restTemplate = new RestTemplate();
	        restTemplate.setRequestFactory(clientHttpRequestFactory());
	        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
	        
	        // 使用 utf-8 编码集的 conver 替换默认的 conver（默认的 string conver 的编码集为 "ISO-8859-1"）
	        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
	        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
	        while (iterator.hasNext()) {
	            HttpMessageConverter<?> converter = iterator.next();
	            if (converter instanceof StringHttpMessageConverter) {
	                iterator.remove();
	            }
	        }
	        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
	        messageConverters.add(fastJsonConfigration.fastJsonHttpMessageConverter());
	        return restTemplate;
	 }  
	 @Bean  
	 public ClientHttpRequestFactory clientHttpRequestFactory(){  
	     HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
	        clientHttpRequestFactory.setHttpClient(HttpClients.createDefault());
	        clientHttpRequestFactory.setConnectTimeout(10000);
	        clientHttpRequestFactory.setReadTimeout(10000);
	        clientHttpRequestFactory.setConnectionRequestTimeout(200);
	        
	        
	
	        
	   return clientHttpRequestFactory;
	        
	}  
}
